//
//  SheZhiViewController.m
//  ZhiBoYuan
//
//  Created by coder_di on 2018/4/17.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "SheZhiViewController.h"
#import "SheZhiTableViewCell.h"
#import "YiJianFanKuiViewController.h"
#import "LogInViewController.h"
#import "GuanYuWoMenVC.h"

@interface SheZhiViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)UIButton *logOutBtn;//退出


@property(nonatomic, assign)BOOL isZuiXin;//判断是不是有更新

@property (nonatomic, strong)NSString *gengXinUrl;//更新的链接

@end

@implementation SheZhiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    
   self.view.backgroundColor = [UIColor whiteColor];
    
    _isZuiXin = YES;
    [self loadData];
    
    [self addTableView];
    
    [self.tableView registerClass:[SheZhiTableViewCell class] forCellReuseIdentifier:@"SheZhiTableViewCell"];
    
    _logOutBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _logOutBtn.frame = CGRectMake(20 * KscreenWidth, 550 * KscreenHeight, ScreenWidth - 40 * KscreenWidth, 60 * KscreenHeight);
    _logOutBtn.backgroundColor = ZhuTiColor;
    [_logOutBtn setTitle:@"退出登录" forState:0];
    [_logOutBtn addTarget: self action:@selector(logOutAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_logOutBtn];
    
}

-(void)loadData{
    
    // 当前应用版本号码   int类型
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{
                       };
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@g=Client&m=Ucenter&a=getVersionForIos",HTTPP] parameter:parameter sucess:^(id responseObject) {
        NSLog(@"%@",responseObject);
        
        NSDictionary *dic = responseObject;
        if ([dic[@"status"] intValue] == 200) {
            
            if ([[dic[@"data"][@"version_info"] valueForKey:@"version_code"]  isEqualToString: appCurVersion]) {
                
                 _isZuiXin = YES;
                
            }else{
                _isZuiXin = NO;
                
                _gengXinUrl = dic[@"data"][@"version_info"][@"apk_address"];
                
                [self.tableView reloadData];
                
            }
        }else{
            
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}

//退出
-(void)logOutAction{
    [ZYUserManager clearUserInfo];
    
    LogInViewController *lvc = [[LogInViewController alloc]init];
    UINavigationController *ncv = [[UINavigationController alloc]initWithRootViewController:lvc];
    self.view.window.rootViewController = ncv;
    
//    LogInViewController *loginVC = [[LogInViewController alloc]init];
//
//    self.view.window.rootViewController = loginVC;
    
//    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:loginVC];
//    [self presentViewController:nav animated:YES completion:nil];
}


-(void)addTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight- NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate        = self;
    _tableView.dataSource      = self;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;

    _tableView.estimatedRowHeight = 44.0f;//推测高度，必须有，可以随便写多少
    
    _tableView.scrollEnabled = NO;
    
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    [self.view addSubview:_tableView];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Navigation
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

 UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,15 * KscreenHeight)];

 view.backgroundColor = hui1Color;

 return view;

 }

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section{

    return 15 * KscreenHeight;

}

#pragma mark -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0 || section == 1) {
        return 1;
    }else{
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifity = @"SheZhiTableViewCell";
    //    MyIndentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifity];
    SheZhiTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[SheZhiTableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifity];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.accessoryType  = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
    
    if (indexPath.section == 0) {
        cell.nameLable.text = @"清除缓存";
        float a = [self readCacheSize];
        if (a == 0.0) {
            cell.detailLable.text = @"0MB";
        }else{
             cell.detailLable.text = [NSString stringWithFormat:@"%.1fMB",a];
        }
       
    }else if (indexPath.section == 1){
//        if (indexPath.row == 0) {
//            cell.nameLable.text = @"帮助";
//        }else{
            cell.nameLable.text = @"意见反馈";
//        }
        
    }else{
        if (indexPath.row == 0) {
            cell.nameLable.text = @"版本说明";
            
//          NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//          NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
//            float aa = [appCurVersionNum floatValue];
//            cell.detailLable.text = [NSString stringWithFormat:@"%.1f",aa];
            if (_isZuiXin == YES) {
                 cell.detailLable.text = @"已是最高版本";
            }else{
                
                cell.detailLable.text = @"有新版本更新";
                cell.detailLable.textColor = [UIColor redColor];
                
            }
           
            
        }else{
            
            cell.nameLable.text = @"关于我们";
        }
        
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 60 * KscreenHeight;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //清理缓存
        [self clearFile];
    }else if (indexPath.section == 1){
            //意见反馈
            YiJianFanKuiViewController *yijianFanKui = [[YiJianFanKuiViewController alloc]init];
            [self.navigationController pushViewController:yijianFanKui animated:YES];
        
    }else{
        if (indexPath.row == 0) {
            //版本说明
            if (_isZuiXin) {
                
            }else{
                NSURL *url = [NSURL URLWithString:_gengXinUrl];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_gengXinUrl]];

                
            }
            
        }else{
            //关于我们
            GuanYuWoMenVC *fenxiangVC = [[GuanYuWoMenVC alloc]init];
            [self.navigationController pushViewController:fenxiangVC animated:YES];
        }
        
    }
    
}


// 获取缓存文件的大小
-( float )readCacheSize
{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    return [ self folderSizeAtPath :cachePath];
}
// 遍历文件夹获得文件夹大小，返回多少 M
- ( float ) folderSizeAtPath:( NSString *) folderPath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
    NSString * fileName;
    long long folderSize = 0 ;
    while ((fileName = [childFilesEnumerator nextObject]) != nil ){
        //获取文件全路径
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        folderSize += [ self fileSizeAtPath :fileAbsolutePath];
    }
    
    return folderSize/( 1024.0 * 1024.0);
    
}
// 计算 单个文件的大小
- ( long long ) fileSizeAtPath:( NSString *) filePath{
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath :filePath]){
        return [[manager attributesOfItemAtPath :filePath error : nil] fileSize];
    }
    return 0;
}

//清除缓存
- (void)clearFile
{
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
    NSArray * files = [[NSFileManager defaultManager ] subpathsAtPath :cachePath];
    //NSLog ( @"cachpath = %@" , cachePath);
    for ( NSString * p in files) {
        
        NSError * error = nil ;
        //获取文件全路径
        NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :p];
        
        if ([[NSFileManager defaultManager ] fileExistsAtPath :fileAbsolutePath]) {
            [[NSFileManager defaultManager ] removeItemAtPath :fileAbsolutePath error :&error];
        }
    }
    
    [self.tableView reloadData];
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"缓存清除成功" message:@"" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil, nil];
    [alertView show];
    
    //读取缓存大小
//    float cacheSize = [self readCacheSize] *1024;
//    self.cacheSize.text = [NSString stringWithFormat:@"%.2fKB",cacheSize];
    
}


@end
